<template>
  <div class="h-full absolute bg-red-100" ref="divRef" :style="sizeStyle">
    <slot v-if="mounted"></slot>
  </div>
</template>

<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    /**
     * 设计稿宽度
     */
    designWidth: number
    /**
     * 设计稿高度
     */
    designHeight: number
    /**
     * 实际视口宽高比例与设计稿宽苞比例不一致时，是否完全填充
     *
     * 完全填充：可能导致界面元素变形，但不会留白
     * 不完全填充：会按比例缩放，界面元素不会变形，但会留白
     */
    fitFull?: boolean
  }>(),
  { fitFull: false }
)

const { designWidth, designHeight, fitFull } = toRefs(props)
const heightScale = ref(1)
const widthScale = ref(1)
const minScale = ref(1)

const mounted = ref(false)

const sizeStyle = computed(() => {
  if (fitFull.value) {
    // 实际宽高比与设计稿宽高比不一致时，会拉伸，而非留白，优点是没有留白，缺点是元素可能拉伸变形
    return {
      transform: `scale(${widthScale.value},${heightScale.value})`,
      transformOrigin: 'top left',
      left: '0',
      top: '0',
      width: `${designWidth.value}px`,
      height: `${designHeight.value}px`
    }
  } else {
    // 实际宽高比与设计稿宽高比不一致时，会留白，优点是元素不会拉伸变形，但会留白
    return {
      transform: `scale(${minScale.value}) translate3d(-50%, -50%, 0)`,
      transformOrigin: 'top left',
      left: '50%',
      top: '50%',
      width: `${designWidth.value}px`,
      height: `${designHeight.value}px`
    }
  }
})

const divRef = ref<HTMLDivElement>()
function getViewPortSize() {
  const width = window.innerWidth
  const height = window.innerHeight
  console.log(width, height)
  return { width, height }
}

function onResize() {
  const { width, height } = getViewPortSize()
  // 计算真实高度与设计稿高度缩放比
  heightScale.value = height / designHeight.value
  // 计算真是宽度与设计稿宽度缩放比
  widthScale.value = width / designWidth.value
  minScale.value = heightScale.value < widthScale.value ? heightScale.value : widthScale.value

  window.widthScale = widthScale.value
  window.heightScale = heightScale.value
  window.minScale = minScale.value
  console.log('执行缩放比计算', window.minScale)
  mounted.value = true
}
function init() {
  onResize()
  window.addEventListener('resize', onResize)
}
function destory() {
  window.removeEventListener('resize', onResize)
}
onMounted(init)

onBeforeMount(destory)
</script>

<style scoped></style>
